package com.yonyou.crm.csns.phonebook.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.enumeration.service.EnumBizServiceImpl;
import com.yonyou.crm.common.field.handler.FieldRelationHandler;
import com.yonyou.crm.common.field.relation.EnumFieldRelation;
import com.yonyou.crm.common.field.relation.FieldRelation;
import com.yonyou.crm.common.field.relation.RefFieldRelation;
import com.yonyou.crm.common.pinyin.PinyinToolkit;
import com.yonyou.crm.csns.phonebook.entity.OrgVO;
import com.yonyou.crm.csns.phonebook.entity.PersonListVO;
import com.yonyou.crm.csns.phonebook.entity.PersonVO;
import com.yonyou.crm.sys.org.service.SysOrgBizServiceImpl;
import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class PersonBizServiceImpl extends BaseBizServiceImpl<PersonVO> {

	@Autowired
	private SysOrgBizServiceImpl sysOrgService;
	
	@Autowired
	private EnumBizServiceImpl enumService;
	
	@Autowired
	private OrgBizServiceImpl orgService;
	
	// 同步用户表和通讯录人员表信息，并转化人名为拼音,同时同步计算组织架构人员数量
	public void synPersonData(){
		dao.deleteSql(PersonVO.class, "synPersonDel");
		dao.saveSql(PersonVO.class, "synPersonSave", null);
		dao.updateSql(PersonVO.class, "synPersonUp");
		dao.updateSql(PersonVO.class, "synPersonUp2");
		dao.updateSql(PersonVO.class, "synPersonUp3");
		
		List<Map<String, Object>> pList = dao.selectList(PersonVO.class, "getNameList");
		for (Map<String, Object> p : pList) {
			String id = p.get("id").toString();
			String name = (String)p.get("name");
			String pinyin = PinyinToolkit.cn2Spell(name, 0);
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("id", id);
			paraMap.put("pinyin", pinyin);
			dao.updateSql(PersonVO.class, "updatePinyin", paraMap);
		}
		
		dao.deleteSql(OrgVO.class, "synOrgDel");
		dao.saveSql(OrgVO.class, "synOrgSave", null);
		
		orgService.countAllByDeptId();
	}
	
	public List<PersonListVO> getPersonList(Map<String, Object> paraMap) {
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long orgId = Long.parseLong(orgIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);
		paraMap.put("orgId", orgId);
		paraMap.put("tenantId", tenantId);
		
		List<PersonVO> personList = dao.selectVoList(PersonVO.class, "getList", paraMap);
		transPerson(personList);
		List<PersonListVO> rsList = new ArrayList<PersonListVO>();
		for (PersonVO vo : personList) {
			PersonListVO listVO = new PersonListVO();
			listVO.setId(vo.getSourceId());
			listVO.setName(vo.getName());
			listVO.setPhonenum(vo.getPhone());
			listVO.setDepartment(vo.getDeptName());
			listVO.setJob(vo.getJob());
			listVO.setPic(vo.getPic());
			listVO.setManage(vo.getManage());
			rsList.add(listVO);
		}
		return rsList;
	}
	
	public List<PersonListVO> getChildrenPersonList(Map<String, Object> paraMap) {
		List<PersonVO> personList = dao.selectVoList(PersonVO.class, "getChildren", paraMap);
		transPerson(personList);
		
		List<PersonListVO> rsList = new ArrayList<PersonListVO>();
		
		for (PersonVO vo : personList) {
			PersonListVO listVO = new PersonListVO();
			listVO.setId(vo.getId());
			listVO.setName(vo.getName());
			listVO.setPic(vo.getPic());
			listVO.setDepartment(vo.getDeptName());
			listVO.setPhonenum(vo.getPhone());
			listVO.setJob(vo.getJob());
			listVO.setManage(vo.getManage());
			
			rsList.add(listVO);
		}
		return rsList;
	}
	
	/*
	 * 通过系统用户信息，同步保存通讯录人员记录
	 */
	public void synFromUser(UserVO userVo, String operation) {
		switch (operation) {
		case "insert":
			saveFromUser(userVo);
			break;
		case "update":
			updateFromUser(userVo);
			break;
		default:
			synPersonData();
			break;
		}
	}
	
	private PersonVO saveFromUser(UserVO userVo) {
		PersonVO vo = new PersonVO();
		Byte source = 1;
		vo.setSource(source);
		vo.setSourceId(userVo.getId());
		
		vo.setName(userVo.getName());
		String namePinyin = PinyinToolkit.cn2Spell(userVo.getName(), 1);
		vo.setNamePinyin(namePinyin);
		vo.setGender(userVo.getGender());
		vo.setGenderName(userVo.getGenderName());
		vo.setEmail(userVo.getEmail());
		vo.setDeptId(userVo.getDeptId());
		vo.setDeptName(userVo.getDeptName());
//        vo.setJob(job); // job来自于角色
		String manage = "N";
		if (userVo.getJob() > 1) {
			manage = "Y";
		}
		vo.setManage(manage);
		vo.setOrgId(userVo.getOrgId());
		vo.setTenantId(userVo.getTenantId());
		vo.setPhone(userVo.getPhone());
		vo.setPic(userVo.getPortraitId());
		
		return super.saveVO(vo);
	}
	
	/*
	 * 通过系统用户信息，同步保存通讯录人员记录
	 */
	public PersonVO updateFromUser(UserVO userVo) {
		// 先判断是否已经存在于通讯录人员表，如果存在，则update，如果不存在，则新增
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("userId", userVo.getId());
		PersonVO oldVo = (PersonVO)dao.selectOne(PersonVO.class, "selectPersonByUserInfo", paraMap);
		if (oldVo == null) {
			return saveFromUser(userVo);
		}
		
		PersonVO vo = new PersonVO();
		vo.setId(oldVo.getId());
		if (userVo.getName() != null && !userVo.getName().equals(oldVo.getName())) {
			vo.setName(userVo.getName());
			String namePinyin = PinyinToolkit.cn2Spell(userVo.getName(), 1);
			vo.setNamePinyin(namePinyin);
		}
		if (userVo.getGender() != null && userVo.getGender().equals(oldVo.getGender())) {
			vo.setGender(userVo.getGender());
		}
		if (userVo.getEmail() != null && userVo.getEmail().equals(oldVo.getEmail())) {
			vo.setEmail(userVo.getEmail());
		}
		if (userVo.getDeptId() != null && userVo.getDeptId().equals(oldVo.getDeptId())) {
			vo.setDeptId(userVo.getDeptId());
		}
		if (userVo.getJob() != null && userVo.getJob().equals(oldVo.getJob())) {
			String manage = "N";
			if (userVo.getJob() > 1) {
				manage = "Y";
			}
			vo.setManage(manage);
		}
		if (userVo.getPhone() != null && userVo.getPhone().equals(oldVo.getPhone())) {
			vo.setPhone(userVo.getPhone());
		}
		if (userVo.getPortraitId() != null && userVo.getPortraitId().equals(oldVo.getPic())) {
			vo.setPic(userVo.getPortraitId());
		}
		
		return super.updateVO(vo);
	}
	
	private List<PersonVO> transPerson(List<PersonVO> personList) {
		
		if (personList != null && personList.size() > 0) {
			
			List<FieldRelation<PersonVO>> relations = new ArrayList<FieldRelation<PersonVO>>();
			relations.add(new RefFieldRelation<PersonVO>(PersonVO.class, "deptId", new String[]{"deptName"}, sysOrgService, "selectFieldsByIds"));
			relations.add(new EnumFieldRelation<PersonVO>(PersonVO.class, "gender", "genderName", enumService, "gender"));
			
			new FieldRelationHandler<PersonVO>().handler(personList, relations);
		}

		return personList;
	}
	
	/*
	 * 按名称搜索用户
	 */
	public List<Map<String, Object>> getUsersByName(String searchKey) {
		
		String tenantIdStr = InvocationInfoProxy.getTenantid();
		Long tenantId = Long.parseLong(tenantIdStr);
		
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("searchKey", searchKey);
		paraMap.put("tenantId", tenantId);
		
		List<PersonVO> personList = dao.selectVoList(PersonVO.class, "getList", paraMap);
		
		List<Map<String, Object>> rsList = new ArrayList<Map<String,Object>>();
		for (PersonVO person:personList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", person.getId());
			map.put("name", person.getName());
			map.put("email", person.getEmail());
			map.put("phone", person.getPhone());
			map.put("manage", person.getManage());
			map.put("job", person.getJob());
			map.put("pic", person.getPic());
			rsList.add(map);
		}
		
		return rsList;
	}
	
}
